<template>
  <div class="app-container page-flex">
    <!-- 顶部搜索卡片（沿用工作日志样式） -->
    <el-card class="box-card mb-4" shadow="hover" v-show="showSearch">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="项目选择" prop="proId">
          <el-select v-model="queryParams.proId" placeholder="请选择项目" clearable filterable remote reserve-keyword
            :remote-method="searchProjects" :loading="projectLoading" style="width: 240px" @change="handleProjectChange"
            @visible-change="handleProjectVisibleChange">
            <el-option v-for="project in projectList" :key="project.id"
              :label="`${project.proName} (${project.proNumber})`" :value="project.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="projectSearchKeyword && projectList.length === 0"> 未找到相关项目 </span>
                <span v-else> 请输入项目名称进行搜索 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="回款节点" prop="receiveId">
          <el-select v-model="queryParams.receiveId" placeholder="请选择回款节点" clearable filterable
            :loading="receiveLoading" style="width: 240px" :disabled="!queryParams.proId"
            @visible-change="handleReceiveVisibleChange" @change="handleReceiveChange">
            <el-option v-for="receive in receiveList" :key="receive.id" :label="receive.nodeTitle"
              :value="receive.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.proId"> 请先选择项目 </span>
                <span v-else> 未找到相关回款节点 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="技术流程" prop="planId">
          <el-select v-model="queryParams.planId" placeholder="请选择技术流程" clearable filterable :loading="planLoading"
            style="width: 240px" :disabled="!queryParams.proId || !queryParams.receiveId"
            @visible-change="handlePlanVisibleChange" @change="handlePlanChange">
            <el-option v-for="plan in planList" :key="plan.id" :label="plan.techFlow" :value="plan.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.proId"> 请先选择项目 </span>
                <span v-else-if="!queryParams.receiveId"> 请先选择回款节点 </span>
                <span v-else> 未找到相关技术流程 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="工作内容" prop="flowId">
          <el-select v-model="queryParams.flowId" placeholder="请选择工作内容" clearable filterable :loading="flowLoading"
            style="width: 240px" :disabled="!queryParams.proId || !queryParams.receiveId || !queryParams.planId"
            @visible-change="handleFlowVisibleChange">
            <el-option v-for="flow in flowList" :key="flow.id" :label="flow.workContent" :value="flow.id" />
            <template #empty>
              <div class="text-center p-2">
                <span v-if="!queryParams.planId"> 请先选择技术流程 </span>
                <span v-else> 未找到相关工作内容 </span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 周日志台账列表卡片 -->
    <el-card class="box-card table-card" v-loading="loading">
      <template #header>
        <el-row :gutter="10" class="mb8" style="align-items:center;">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['project:weeklog:export']">导出</el-button>
          </el-col>
          <el-col :span="10" style="display: flex; align-items: center; gap: 8px">
            <el-select v-model="sortField" placeholder="选择排序字段" clearable style="width: 170px"
              @change="handleSortChange">
              <el-option label="记录人" value="recordBy" />
              <el-option label="记录时间" value="recordTime" />
              <el-option label="项目名称" value="proId" />
              <el-option label="回款名称" value="receiveId" />
              <el-option label="技术流程" value="planId" />
              <el-option label="工作内容" value="flowId" />
              <el-option label="周期序列" value="weekOrder" />
            </el-select>
            <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'" @click="toggleSortOrder"
              type="info" plain size="small">
              {{ sortOrder === 'asc' ? '正序' : '逆序' }}
            </el-button>
          </el-col>
          <div style="margin-left: auto; display: flex; align-items: center; gap:8px;">
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </div>
        </el-row>
      </template>

      <!-- 周日志表格 -->
      <div class="worklog-container">
        <el-table :data="weeklogList" border style="width: 100%" row-key="id" height="100%" class="flex-table">
          <el-table-column label="序号" align="center" width="80" fixed="left">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="记录时间" align="center" fixed="left" prop="recordTime">
            <template #default="scope">
              <span>{{ scope.row.recordTime ? parseTime(scope.row.recordTime, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200" label="项目名称" align="center" fixed="left" prop="proName" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.proName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200" label="回款名称" align="left" prop="receiveName" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.receiveName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200" label="技术流程" align="left" prop="techFlow" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.techFlow || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="工作内容" align="left" prop="workContent" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.workContent || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="计划开始时间" align="center" prop="planStartTime">
            <template #default="scope">
              <span>{{ scope.row.planStartTime ? parseTime(scope.row.planStartTime, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="计划结束时间" align="center" prop="planEndTime">
            <template #default="scope">
              <span>{{ scope.row.planEndTime ? parseTime(scope.row.planEndTime, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="详细工作计划" align="left" prop="detailWorkPlan" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.detailWorkPlan || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="本周工作计划" align="left" prop="thisWeekPlan" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.thisWeekPlan || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="120" label="周期序列" align="center" prop="weekOrder">
            <template #default="scope">
              <el-tag v-if="scope.row.weekOrder !== undefined && scope.row.weekOrder !== null" type="primary" size="small">
                第{{ scope.row.weekOrder }}周
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="本周完成情况" align="left" prop="thisWeekCase" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.thisWeekCase" type="textarea" :rows="3"
                resize="vertical" />
              <span v-else class="text-overflow">{{ scope.row.thisWeekCase || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="下周计划" align="left" prop="nextWeekPlan" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.nextWeekPlan" type="textarea" :rows="3"
                resize="vertical" />
              <span v-else>{{ scope.row.nextWeekPlan || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160" label="节点完成(%)" align="center" prop="nodeCompleteRate">
            <template #default="scope">
              <PercentageInput v-if="scope.row.isEditing" v-model="scope.row.nodeCompleteRate" :min="0" :max="100"
                :precision="2" />
              <span v-else>{{ formatPercent(scope.row.nodeCompleteRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="记录人" align="center" prop="recordName">
            <template #default="scope">
              <span>{{ scope.row.recordName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="300" label="备注" align="left" prop="remark" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" :rows="3"
                resize="vertical" />
              <span v-else>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="180" label="创建时间" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <template v-if="scope.row.isEditing">
                <el-button size="small" type="primary" @click="saveRow(scope.row)"
                  :loading="scope.row.saving">保存</el-button>
                <el-button size="small" type="danger" @click="cancelEdit(scope.row)"
                  :disabled="scope.row.saving">取消</el-button>
              </template>
              <template v-else>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="editRow(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无周日志数据" />
          </template>
        </el-table>
      </div>

      <!-- 固定底部分页 -->
      <div class="pagination-container" v-if="weeklogList.length > 0">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { pageListForQuery } from '@/api/project/init/proInfo';
import { getReceiveMoneyNodesByProId } from '@/api/project/receive';
import { listProFlow } from '@/api/project/plan/flow';
import { listProPlan } from '@/api/project/plan';
import { listWeeklogRecord, updateWeeklogRecord } from '@/api/project/log/weeklog';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import type { ProFlowVO } from '@/api/project/plan/flow/types';
import PercentageInput from '@/components/PercentageInput/index.vue';

const { proxy } = getCurrentInstance() as any;

// 列表
const weeklogList = ref<any[]>([]);

// 关联下拉列表
const projectList = ref<ProInfoVO[]>([]);
const flowList = ref<ProFlowVO[]>([]);
const planList = ref<any[]>([]);
const receiveList = ref<any[]>([]);
const projectLoading = ref(false);
const flowLoading = ref(false);
const planLoading = ref(false);
const receiveLoading = ref(false);

// 搜索关键词
const projectSearchKeyword = ref('');

// 分页与查询参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  proId: undefined,
  receiveId: undefined as any,
  planId: undefined as any,
  flowId: undefined,
  params: {}
});

// 排序
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('desc');

// 总条数与加载
const total = ref(0);
const loading = ref(false);

const showSearch = ref(true);
const getList = () => handleQuery();

// 百分比格式化
const formatPercent = (val: any) => {
  if (val === null || val === undefined) return '-';
  const num = Number(val);
  if (Number.isNaN(num)) return '-';
  return `${num}%`;
};

// 远程搜索项目
const searchProjects = (query: string) => {
  projectSearchKeyword.value = query;
  getProjectList(query);
};

// 获取项目列表
const getProjectList = async (searchKeyword = '') => {
  try {
    projectLoading.value = true;
    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50,
      auditStatus: '3',
      proName: searchKeyword || undefined
    });
    projectList.value = res.rows || [];
  } catch (error) {
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

// 获取回款节点
const getReceiveList = async (proId: number | string) => {
  try {
    receiveLoading.value = true;
    const res = await getReceiveMoneyNodesByProId(proId);
    receiveList.value = res.data || [];
  } catch (e) {
    receiveList.value = [];
  } finally {
    receiveLoading.value = false;
  }
};

// 获取计划列表（基于回款）
const getPlanList = async (receiveId: number | string) => {
  try {
    planLoading.value = true;
    const res = await listProPlan({ receiveId: receiveId } as any);
    planList.value = (res.data || res.rows || []) as any[];
  } catch (e) {
    planList.value = [];
  } finally {
    planLoading.value = false;
  }
};

// 获取流程列表（基于计划）
const getFlowList = async (planId: number | string) => {
  if (!planId) {
    flowList.value = [];
    return;
  }
  try {
    flowLoading.value = true;
    const res = await listProFlow({ planId: planId } as any);
    flowList.value = (res.data || []).map((flow: any) => ({ id: flow.id, workContent: flow.workContent })) as any;
  } catch (e) {
    flowList.value = [];
  } finally {
    flowLoading.value = false;
  }
};

// 下拉显示时加载
const handleProjectVisibleChange = (visible: boolean) => {
  if (visible && projectList.value.length === 0) getProjectList();
};
const handleReceiveVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.proId && receiveList.value.length === 0) getReceiveList(queryParams.value.proId);
};
const handlePlanVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.receiveId && planList.value.length === 0) getPlanList(queryParams.value.receiveId);
};
const handleFlowVisibleChange = (visible: boolean) => {
  if (visible && queryParams.value.planId && flowList.value.length === 0) getFlowList(queryParams.value.planId);
};

// 联动变化
const handlePlanChange = (val: any) => {
  queryParams.value.flowId = undefined;
  flowList.value = [];
  if (val) getFlowList(val);
};
const handleReceiveChange = (val: any) => {
  queryParams.value.planId = undefined;
  queryParams.value.flowId = undefined;
  planList.value = [];
  flowList.value = [];
  if (val) getPlanList(val);
};
const handleProjectChange = (value: number | string | undefined) => {
  queryParams.value.receiveId = undefined as any;
  queryParams.value.planId = undefined as any;
  queryParams.value.flowId = undefined;
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  if (value) getReceiveList(value);
};

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getWeeklogListData();
};

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    proId: undefined,
    receiveId: undefined as any,
    planId: undefined as any,
    flowId: undefined,
    params: {}
  };
  sortField.value = undefined;
  sortOrder.value = 'desc';
  projectList.value = [];
  receiveList.value = [];
  planList.value = [];
  flowList.value = [];
  projectSearchKeyword.value = '';
  handleQuery();
};

const handleSortChange = () => {
  if (sortField.value && !sortOrder.value) sortOrder.value = 'desc';
  handleQuery();
};
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

// 获取列表
const getWeeklogListData = async () => {
  try {
    loading.value = true;
    const params = { ...queryParams.value } as any;
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    if (!params.proId) delete params.proId;
    if (!params.receiveId) delete params.receiveId;
    if (!params.planId) delete params.planId;
    if (!params.flowId) delete params.flowId;

    const res = await listWeeklogRecord(params);
    weeklogList.value = (res.rows || []).map((item: any) => ({ ...item, isEditing: false, saving: false, originalData: null }));
    total.value = res.total || 0;
  } catch (e) {
    ElMessage.error('获取周日志列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getWeeklogListData();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getWeeklogListData();
};

onMounted(() => {
  getWeeklogListData();
});

// 行内编辑相关
const editRow = (row: any) => {
  row.originalData = JSON.parse(JSON.stringify(row));
  row.isEditing = true;
  row.saving = false;
};

const cancelEdit = (row: any) => {
  if (row.originalData) {
    Object.assign(row, row.originalData);
    row.isEditing = false;
    row.originalData = null;
  }
};

const saveRow = async (row: any) => {
  row.saving = true;
  try {
    const payload = {
      id: row.id,
      proId: row.proId,
      receiveId: row.receiveId,
      planId: row.planId,
      flowId: row.flowId,
      weeklogId: row.weeklogId,
      weekOrder: row.weekOrder,
      version: row.version,
      thisWeekCase: row.thisWeekCase,
      nextWeekPlan: row.nextWeekPlan,
      nodeCompleteRate: row.nodeCompleteRate,
      remark: row.remark
    } as any;
    await updateWeeklogRecord(payload);
    ElMessage.success('保存成功');
    row.isEditing = false;
    row.originalData = null;
    getWeeklogListData();
  } catch (e) {
    ElMessage.error('保存失败');
  } finally {
    row.saving = false;
  }
};

/**
 * 导出按钮操作
 */
const handleExport = () => {
  // 构建导出参数，包含当前查询条件
  const params = { ...queryParams.value };

  // 移除分页参数，导出全部数据
  delete params.pageNum;
  delete params.pageSize;

  // 调用下载方法
  proxy?.download('pro/weeklog/record/export', params, `weeklog_record_${new Date().getTime()}.xlsx`, 'post');
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.search-form {
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  column-gap: 16px;
  row-gap: 12px;
}

.search-form .el-form-item {
  margin: 0 !important;
}

.worklog-container {
  position: relative;
  margin-top: 20px;
  flex: 1;

  :deep(.el-table) {
    .el-table__cell {
      vertical-align: middle;
    }
  }
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

/* —— 以下样式与工作日志record保持一致 —— */
.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
}

.worklog-container :deep(.el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-select .el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-date-editor.el-input) {
  width: 100%;
}

.worklog-container :deep(.el-date-editor .el-input__wrapper) {
  min-height: 28px;
}

.worklog-container :deep(.el-textarea__inner) {
  min-height: 60px;
  resize: vertical;
}

.worklog-container :deep(.el-input-number) {
  width: 100%;
}

.worklog-container :deep(.el-input-number .el-input__wrapper) {
  min-height: 28px;
}

/* 搜索下拉等细节优化（与工作日志一致） */
:deep(.el-select-dropdown__empty) {
  padding: 16px 0;
  color: #909399;
  font-size: 14px;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-select-dropdown__item) {
  padding: 10px 20px;
  min-height: 40px;
  line-height: 1.4;
  white-space: nowrap;
  height: auto;
}

:deep(.el-select-dropdown__item.is-hovering) {
  background-color: var(--el-color-primary-light-9);
}

/* 小尺寸组件视觉一致 */
.worklog-container :deep(.is-error .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.worklog-container :deep(.is-error .el-input__inner) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-date-editor .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.worklog-container :deep(.is-error .el-input-number .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.worklog-container :deep(.is-error .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-date-editor .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

.worklog-container :deep(.is-error .el-input-number .el-input__wrapper:hover) {
  border-color: #f56c6c !important;
}

@media (max-width: 768px) {
  .app-container {
    padding: 8px;
  }

  .search-form {
    column-gap: 8px;
    row-gap: 8px;
  }
}
</style>
